  //
  //  FavoriteController.swift
  //  hello
  //
  //  Created by 赵康 on 2024/12/17.
  //

import Vapor
import Fluent

struct FavoriteController: RouteCollection {
  private let favoriteService = FavoriteService()
  
  func boot(routes: any RoutesBuilder) throws {
    let favorites = routes.grouped("\(RouteEnum.favorites.rawValue)")
    
    let protected = favorites.grouped(AuthMiddleware())
    protected.post("\(RouteEnum.create.rawValue)", ":albumID", use: create)
    protected.get("\(RouteEnum.fetch.rawValue)", use: fetch)
    protected.delete("\(RouteEnum.delete.rawValue)", ":albumID", use: delete)
    
    // 收藏夹相关路由
    let folders = protected.grouped("\(RouteEnum.folders.rawValue)")
    folders.get("\(RouteEnum.fetchFolders.rawValue)", use: fetchFolders)
    folders.post("\(RouteEnum.createFolder.rawValue)", use: createFolder)
    folders.put("\(RouteEnum.renameFolder.rawValue)", ":folderID", use: renameFolder)
    folders.delete("\(RouteEnum.deleteFolder.rawValue)", ":folderID", use: deleteFolder)
    folders.post("\(RouteEnum.addToFolder.rawValue)", use: addToFolder)
    folders.delete("\(RouteEnum.removeFromFolder.rawValue)", ":folderID", ":albumID", use: removeFromFolder)
    folders.get(":folderID", use: getFolderAlbums)
    
    // 新增收藏夹排序相关路由
    folders.put("\(RouteEnum.updateFoldersOrder.rawValue)", use: updateFoldersOrder)
    folders.put("\(RouteEnum.updateAlbumsOrder.rawValue)", ":folderID", use: updateAlbumsOrder)
    folders.put("\(RouteEnum.saveSortPreference.rawValue)", ":folderID", use: saveSortPreference)
  }
  
  @Sendable
  func create(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let albumID = try req.parameters.require("albumID", as: UUID.self)
    
    req.logger.info("收藏控制器: 开始处理创建收藏请求, userID=\(userID), albumID=\(albumID)")
    
    // 使用FavoriteService创建收藏
    let response = try await favoriteService.createFavorite(userID: userID, albumID: albumID, req: req)
    
    req.logger.info("收藏控制器: 收藏创建成功, 开始清除缓存")
    
    // 清除用户的收藏相关缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 创建收藏请求处理完成")
    return response
  }
  
  @Sendable
  func delete(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let albumID = try req.parameters.require("albumID", as: UUID.self)
    
    req.logger.info("收藏控制器: 开始处理删除收藏请求, userID=\(userID), albumID=\(albumID)")
    
    // 使用FavoriteService删除收藏
    let response = try await favoriteService.deleteFavorite(userID: userID, albumID: albumID, req: req)
    
    req.logger.info("收藏控制器: 收藏删除成功, 开始清除缓存")
    
    // 清除用户的收藏相关缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 删除收藏请求处理完成")
    return response
  }
  
  @Sendable
  func fetch(_ req: Request) async throws -> [AlbumResponse] {
    let userID = try req.authenticatedUserID
    let favoriteCache = FavoriteCache(req: req)
    
    req.logger.info("收藏控制器: 开始处理获取收藏列表请求, userID=\(userID)")
    
    // 尝试从缓存获取
    if let cachedFavorites = try await favoriteCache.getCachedFavorites(forUserID: userID, on: req) {
      req.logger.info("收藏控制器: 从缓存获取用户 \(userID) 的收藏列表, 专辑数量=\(cachedFavorites.count)")
      return cachedFavorites
    }
    
    req.logger.info("收藏控制器: 缓存未命中, 从数据库获取收藏列表")
    
    // 从数据库获取
    let favorites = try await favoriteService.fetchFavorites(userID: userID, req: req)
    
    req.logger.info("收藏控制器: 从数据库获取成功, 专辑数量=\(favorites.count), 开始缓存结果")
    
    // 缓存结果
    try await favoriteCache.cacheFavorites(favorites, forUserID: userID, on: req)
    
    req.logger.info("收藏控制器: 获取收藏列表请求处理完成")
    return favorites
  }
  
  // 获取用户所有收藏夹
  @Sendable
  func fetchFolders(_ req: Request) async throws -> [FolderResponse] {
    let userID = try req.authenticatedUserID
    let favoriteCache = FavoriteCache(req: req)
    
    req.logger.info("收藏控制器: 开始处理获取收藏夹列表请求, userID=\(userID)")
    
    // 尝试从缓存获取
    if let cachedFolders = try await favoriteCache.getCachedFolders(forUserID: userID, on: req) {
      req.logger.info("收藏控制器: 从缓存获取用户 \(userID) 的收藏夹列表, 数量=\(cachedFolders.count)")
      return cachedFolders
    }
    
    req.logger.info("收藏控制器: 缓存未命中, 从数据库获取收藏夹列表")
    
    // 从数据库获取
    let folders = try await favoriteService.fetchFolders(userID: userID, req: req)
    
    req.logger.info("收藏控制器: 从数据库获取成功, 收藏夹数量=\(folders.count), 开始缓存结果")
    
    // 缓存结果
    try await favoriteCache.cacheFolders(folders, forUserID: userID, on: req)
    
    req.logger.info("收藏控制器: 获取收藏夹列表请求处理完成")
    return folders
  }
  
  // 创建收藏夹
  @Sendable
  func createFolder(_ req: Request) async throws -> FolderResponse {
    let userID = try req.authenticatedUserID
    let data = try req.content.decode(CreateFolderRequest.self)
    
    req.logger.info("收藏控制器: 开始处理创建收藏夹请求, userID=\(userID), name=\(data.name), isDefault=\(data.isDefault ?? false)")
    
    // 创建收藏夹
    let folder = try await favoriteService.createFolder(
      userID: userID,
      name: data.name,
      isDefault: data.isDefault,
      req: req
    )
    
    req.logger.info("收藏控制器: 收藏夹创建成功, folderID=\(folder.id), name=\(folder.name), 开始清除缓存")
    
    // 清除用户的收藏夹缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 创建收藏夹请求处理完成")
    return folder
  }
  
  // 重命名收藏夹
  @Sendable
  func renameFolder(_ req: Request) async throws -> FolderResponse {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    let data = try req.content.decode(RenameFolderRequest.self)
    
    req.logger.info("收藏控制器: 开始处理重命名收藏夹请求, userID=\(userID), folderID=\(folderID), newName=\(data.name)")
    
    // 重命名收藏夹
    let folder = try await favoriteService.renameFolder(
      userID: userID,
      folderID: folderID,
      newName: data.name,
      req: req
    )
    
    req.logger.info("收藏控制器: 收藏夹重命名成功, folderID=\(folder.id), 新名称=\(folder.name), 开始清除缓存")
    
    // 清除用户的收藏夹缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 重命名收藏夹请求处理完成")
    return folder
  }
  
  // 删除收藏夹
  @Sendable
  func deleteFolder(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    
    req.logger.info("收藏控制器: 开始处理删除收藏夹请求, userID=\(userID), folderID=\(folderID)")
    
    // 删除收藏夹
    let response = try await favoriteService.deleteFolder(
      userID: userID,
      folderID: folderID,
      req: req
    )
    
    req.logger.info("收藏控制器: 收藏夹删除成功, 开始清除缓存")
    
    // 清除用户的收藏夹缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 删除收藏夹请求处理完成")
    return response
  }
  
  // 添加专辑到收藏夹
  @Sendable
  func addToFolder(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let data = try req.content.decode(AddToFolderRequest.self)
    
    req.logger.info("收藏控制器: 开始处理添加专辑到收藏夹请求, userID=\(userID), albumID=\(data.albumID), folderID=\(data.folderID)")
    
    // 添加专辑到收藏夹
    let response = try await favoriteService.addAlbumToFolder(
      userID: userID,
      albumID: data.albumID,
      folderID: data.folderID,
      req: req
    )
    
    req.logger.info("收藏控制器: 添加专辑到收藏夹成功, 开始清除缓存")
    
    // 清除用户的收藏夹缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 添加专辑到收藏夹请求处理完成")
    return response
  }
  
  // 从收藏夹移除专辑
  @Sendable
  func removeFromFolder(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    let albumID = try req.parameters.require("albumID", as: UUID.self)
    
    req.logger.info("收藏控制器: 开始处理从收藏夹移除专辑请求, userID=\(userID), folderID=\(folderID), albumID=\(albumID)")
    
    // 从收藏夹移除专辑
    let response = try await favoriteService.removeAlbumFromFolder(
      userID: userID,
      folderID: folderID,
      albumID: albumID,
      req: req
    )
    
    req.logger.info("收藏控制器: 从收藏夹移除专辑成功, 开始清除缓存")
    
    // 清除用户的收藏夹缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 从收藏夹移除专辑请求处理完成")
    return response
  }
  
  // 获取收藏夹内的专辑
  @Sendable
  func getFolderAlbums(_ req: Request) async throws -> [AlbumResponse] {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    
    // 获取排序选项
    let sortOrderString = req.query[String.self, at: "sortOrder"] ?? FavoritesSortOrder.titleAsc.rawValue
    let sortOrder = FavoritesSortOrder(rawValue: sortOrderString) ?? .titleAsc
    
    req.logger.info("收藏控制器: 开始处理获取收藏夹内专辑请求, userID=\(userID), folderID=\(folderID), sortOrder=\(sortOrder.rawValue)")
    
    let favoriteCache = FavoriteCache(req: req)
    
    // 尝试从缓存获取
    if let cachedAlbums = try await favoriteCache.getCachedAlbumsInFolder(
      forUserID: userID,
      folderID: folderID,
      sortOrder: sortOrder,
      on: req
    ) {
      req.logger.info("收藏控制器: 从缓存获取用户 \(userID) 的收藏夹 \(folderID) 中的专辑, 专辑数量=\(cachedAlbums.count)")
      return cachedAlbums
    }
    
    req.logger.info("收藏控制器: 缓存未命中, 从数据库获取收藏夹内专辑")
    
    // 从数据库获取
    let albums = try await favoriteService.getAlbumsInFolder(
      userID: userID,
      folderID: folderID,
      sortOrder: sortOrder,
      req: req
    )
    
    req.logger.info("收藏控制器: 从数据库获取成功, 专辑数量=\(albums.count), 开始缓存结果")
    
    // 缓存结果
    try await favoriteCache.cacheAlbumsInFolder(
      albums,
      forUserID: userID,
      folderID: folderID,
      sortOrder: sortOrder,
      on: req
    )
    
    req.logger.info("收藏控制器: 获取收藏夹内专辑请求处理完成")
    return albums
  }
  
  // 更新收藏夹顺序
  @Sendable
  func updateFoldersOrder(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let data = try req.content.decode(UpdateFoldersOrderRequest.self)
    
    req.logger.info("收藏控制器: 开始处理更新收藏夹顺序请求, userID=\(userID), 收藏夹数量=\(data.folderOrders.count)")
    
    // 更新收藏夹顺序
    let response = try await favoriteService.updateFoldersOrder(
      userID: userID,
      folderOrders: data.folderOrders,
      req: req
    )
    
    req.logger.info("收藏控制器: 更新收藏夹顺序成功, 开始清除缓存")
    
    // 清除用户的收藏相关缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 更新收藏夹顺序请求处理完成")
    return response
  }
  
  // 更新专辑顺序
  @Sendable
  func updateAlbumsOrder(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    let data = try req.content.decode(UpdateAlbumsOrderRequest.self)
    
    req.logger.info("收藏控制器: 开始处理更新专辑顺序请求, userID=\(userID), folderID=\(folderID), 专辑数量=\(data.albumOrders.count)")
    
    // 更新专辑顺序
    let response = try await favoriteService.updateAlbumsOrder(
      userID: userID,
      folderID: folderID,
      albumOrders: data.albumOrders,
      req: req
    )
    
    req.logger.info("收藏控制器: 更新专辑顺序成功, 开始清除缓存")
    
    // 清除用户的收藏相关缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 更新专辑顺序请求处理完成")
    return response
  }
  
  // 保存排序偏好
  @Sendable
  func saveSortPreference(_ req: Request) async throws -> BasicResponse {
    let userID = try req.authenticatedUserID
    let folderID = try req.parameters.require("folderID", as: UUID.self)
    let data = try req.content.decode(SaveSortPreferenceRequest.self)
    
    req.logger.info("收藏控制器: 开始处理保存排序偏好请求, userID=\(userID), folderID=\(folderID), sortOrder=\(data.sortOrder)")
    
    // 保存排序偏好
    let response = try await favoriteService.saveSortPreference(
      userID: userID,
      folderID: folderID,
      sortOrder: data.sortOrder,
      req: req
    )
    
    req.logger.info("收藏控制器: 保存排序偏好成功, 开始清除缓存")
    
    // 清除用户的收藏相关缓存
    try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
    
    req.logger.info("收藏控制器: 保存排序偏好请求处理完成")
    return response
  }
}
